import axios from 'axios'

// Home page service: fetch banners, services, and user status
// In absence of a real backend, provides mocked responses with the same shapes

const API_PREFIX = import.meta?.env?.VITE_API_PREFIX || ''

export async function fetchHomeConfig() {
  // Intended real call
  if (API_PREFIX) {
    const [bannersRes, servicesRes, announcementsRes, articlesRes] = await Promise.all([
      axios.get(`${API_PREFIX}/home/banners`),
      axios.get(`${API_PREFIX}/home/services`),
      axios.get(`${API_PREFIX}/home/announcements`),
      axios.get(`${API_PREFIX}/home/articles`)
    ])
    return {
      banners: bannersRes.data?.banners || [],
      services: servicesRes.data?.services || [],
      announcements: announcementsRes.data?.announcements || [],
      articles: articlesRes.data?.articles || []
    }
  }

  // Mocked config
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        banners: [
          { id: 'b1', title: '健康生活 轻松简单', color: '#4CAF50', jumpType: '内部路径', target: '/health' },
          { id: 'b2', title: '智慧医疗 科技护航', color: '#2196F3', jumpType: '外链', target: 'https://example.com' },
          { id: 'b3', title: '专业团队 贴心服务', color: '#FF9800', jumpType: '小程序', target: 'wx12345:pages/index/index' }
        ],
        services: [
          // 门诊 (outpatient)
          { key: '门诊挂号', icon: '📅', text: '门诊挂号', path: '/register', category: 'outpatient' },
          { key: '门诊缴费', icon: '💰', text: '门诊缴费', path: '/payment', category: 'outpatient' },
          { key: '报告查询', icon: '📋', text: '报告查询', path: '/report', category: 'outpatient' },
          { key: '候诊查询', icon: '⏰', text: '候诊查询', path: '/queue', category: 'outpatient' },
          { key: '自助开单', icon: '📝', text: '自助开单', path: '/order', category: 'outpatient' },
          { key: '医技预约', icon: '🔬', text: '医技预约', path: '/skill', category: 'outpatient' },
          { key: '我的复诊', icon: '🔄', text: '我的复诊', path: '/revisit', category: 'outpatient' },
          { key: '自助取号', icon: '🎫', text: '自助取号', path: '/ticket', category: 'outpatient' },
          // 住院 (inpatient)
          { key: '入院登记', icon: '🏥', text: '入院登记', path: '/inpatient/register', category: 'inpatient' },
          { key: '住院预交', icon: '💳', text: '住院预交', path: '/inpatient/deposit', category: 'inpatient' },
          { key: '住院报告', icon: '📑', text: '住院报告', path: '/inpatient/report', category: 'inpatient' },
          { key: '住院日清单', icon: '📄', text: '住院日清单', path: '/inpatient/daily', category: 'inpatient' },
          { key: '住院陪护证', icon: '🆔', text: '住院陪护证', path: '/inpatient/pass', category: 'inpatient' },
          // 综合 (comprehensive)
          { key: '代寄服务', icon: '📦', text: '代寄服务', path: '/service/express', category: 'comprehensive' },
          { key: '中药代煎', icon: '🍵', text: '中药代煎', path: '/service/decoction', category: 'comprehensive' },
          { key: '价目查询', icon: '💰', text: '价目查询', path: '/service/price', category: 'comprehensive' },
          { key: '就医指南', icon: '📖', text: '就医指南', path: '/service/guide', category: 'comprehensive' }
        ],
        announcements: [
          '智慧医院即将上线通知',
          '新功能上线：在线问诊服务',
          '专家门诊预约开放中',
          '体检套餐优惠活动进行中'
        ],
        articles: [
          {
            id: 'a1',
            title: '世界糖尿病日，应注意什么？',
            tag: '#健康养生',
            emoji: '🩸',
            likes: 520,
            views: 2000
          },
          {
            id: 'a2',
            title: '冬季呼吸道疾病防护指南',
            tag: '#健康科普',
            emoji: '🧣',
            likes: 320,
            views: 1500
          }
        ]
      })
    }, 600)
  })
}

export async function fetchUserHomeStatus() {
  if (API_PREFIX) {
    const res = await axios.get(`${API_PREFIX}/home/userStatus`)
    return res.data
  }

  // Mock user dynamic status
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        hasPendingPayment: true,
        pendingPaymentCount: 1,
        hasTodayRegistration: true,
        todayRegistrations: 1
      })
    }, 400)
  })
}

export function openBannerTarget(navigate, banner) {
  // Supports: internal route, external link, miniapp deep link placeholder
  if (!banner) return
  const { jumpType, target } = banner
  if (jumpType === 'internal' || jumpType === '内部路径') {
    navigate(target)
  } else if (jumpType === 'external' || jumpType === '外链') {
    window.location.href = target
  } else if (jumpType === 'miniapp' || jumpType === '小程序') {
    // Placeholder: integrate with real miniapp SDK in host app
    console.info('[miniapp-open]', target)
  }
}

export async function fetchArticleById(id) {
  if (API_PREFIX) {
    const res = await axios.get(`${API_PREFIX}/home/articles/${id}`)
    return res.data
  }
  // Mock find by id
  const all = [
    {
      id: 'a1',
      title: '世界糖尿病日，应注意什么？',
      tag: '#健康养生',
      emoji: '🩸',
      likes: 520,
      views: 2000,
      content: '控制饮食、规律运动、监测血糖、遵医用药，关注足部与视网膜健康。'
    },
    {
      id: 'a2',
      title: '冬季呼吸道疾病防护指南',
      tag: '#健康科普',
      emoji: '🧣',
      likes: 320,
      views: 1500,
      content: '勤洗手、戴口罩、常通风，接种疫苗，出现症状及时就医，避免人群聚集。'
    }
  ]
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(all.find(a => a.id === id) || all[0])
    }, 300)
  })
}

export async function fetchArticles({ page = 1, pageSize = 5 } = {}) {
  if (API_PREFIX) {
    const res = await axios.get(`${API_PREFIX}/home/articles`, { params: { page, pageSize } })
    return res.data
  }
  // Mock a larger list
  const base = [
    { id: 'a1', title: '世界糖尿病日，应注意什么？', tag: '#健康养生', emoji: '🩸', likes: 520, views: 2000 },
    { id: 'a2', title: '冬季呼吸道疾病防护指南', tag: '#健康科普', emoji: '🧣', likes: 320, views: 1500 },
    { id: 'a3', title: '高血压日常管理要点', tag: '#慢病管理', emoji: '🩺', likes: 210, views: 1200 },
    { id: 'a4', title: '儿童发热怎么办？', tag: '#儿科科普', emoji: '🧸', likes: 260, views: 1300 },
    { id: 'a5', title: '春季过敏防护建议', tag: '#过敏科普', emoji: '🌸', likes: 180, views: 900 },
    { id: 'a6', title: '规律作息与心血管健康', tag: '#心内科', emoji: '🫀', likes: 300, views: 1600 },
    { id: 'a7', title: '骨质疏松饮食与锻炼', tag: '#骨科', emoji: '🦴', likes: 140, views: 800 }
  ]
  const start = (page - 1) * pageSize
  const items = base.slice(start, start + pageSize)
  const hasMore = start + pageSize < base.length
  return new Promise(resolve => setTimeout(() => resolve({ items, hasMore, page }), 400))
}

export default {
  fetchHomeConfig,
  fetchUserHomeStatus,
  openBannerTarget,
  fetchArticleById,
  fetchArticles
}

